/**
 * 生成图片缩略图
 * @param file 原始图片文件
 * @param options 配置选项
 * @returns 返回缩略图的File对象Promise
 */
export async function generateThumbnail(
    file: File,
    options: {
        maxWidth?: number;
        maxHeight?: number;
        quality?: number;
        mimeType?: string;
    } = {}
): Promise<File> {
    // 默认配置
    const {
        maxWidth = 200,
        maxHeight = 200,
        quality = 0.8,
        mimeType = 'image/jpeg'
    } = options;

    // 验证输入是否为图片
    if (!file.type.match(/^image\//)) {
        throw new Error('File is not an image');
    }

    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (event) => {
            const img = new Image();
            img.onload = () => {
                try {
                    // 计算缩略图尺寸
                    const { width, height } = calculateAspectRatioFit(
                        img.width,
                        img.height,
                        maxWidth,
                        maxHeight
                    );

                    // 创建canvas绘制缩略图
                    const canvas = document.createElement('canvas');
                    canvas.width = width;
                    canvas.height = height;
                    const ctx = canvas.getContext('2d');

                    if (!ctx) {
                        throw new Error('Could not get canvas context');
                    }

                    // 绘制缩略图
                    ctx.drawImage(img, 0, 0, width, height);

                    // 转换为Blob
                    canvas.toBlob(
                        (blob) => {
                            if (!blob) {
                                reject(new Error('Failed to create blob from canvas'));
                                return;
                            }

                            // 转换为File对象
                            const thumbnailFile = new File([blob], file.name, {
                                type: mimeType,
                                lastModified: Date.now()
                            });
                            resolve(thumbnailFile);
                        },
                        mimeType,
                        quality
                    );
                } catch (error) {
                    reject(error);
                }
            };

            img.onerror = () => {
                reject(new Error('Failed to load image'));
            };

            img.src = event.target?.result as string;
        };

        reader.onerror = () => {
            reject(new Error('Failed to read file'));
        };

        reader.readAsDataURL(file);
    });
}

/**
 * 计算保持宽高比的适配尺寸
 * @param srcWidth 原始宽度
 * @param srcHeight 原始高度
 * @param maxWidth 最大宽度
 * @param maxHeight 最大高度
 * @returns 计算后的宽度和高度
 */
function calculateAspectRatioFit(
    srcWidth: number,
    srcHeight: number,
    maxWidth: number,
    maxHeight: number
): { width: number; height: number } {
    const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
    return {
        width: srcWidth * ratio,
        height: srcHeight * ratio
    };
}